import axios from 'axios'
import { Message, MessageBox } from 'element-ui'
import store from '../store'
import { getToken } from '@/utils/auth'

// 创建axios实例
const service = axios.create({
  baseURL: '/api', // api的base_url
  timeout: 30000 // 请求超时时间
})
const config = config => {
  if (!config.params) {
    config.params = {}
  }
  if (getToken()) {
    config.params.tokenId = getToken()
    sessionStorage.setItem('tokenId', getToken())
  }
  return config
}
// request拦截器
service.interceptors.request.use(config, error => {
  Promise.reject(error)
})

// respone拦截器
service.interceptors.response.use(
  response => {
    const res = response.data
    sessionStorage.setItem('baseURL', response.config.baseURL)
    if (res.status !== 0) {
      // 50008:非法的token; 50012:其他客户端登录了;  50014:Token 过期了;
      if (
        res.status === 50008 ||
        res.status === 50012 ||
        res.status === 50014
      ) {
        MessageBox.confirm(
          '你已被登出，可以取消继续留在该页面，或者重新登录',
          '确定登出',
          {
            confirmButtonText: '重新登录',
            cancelButtonText: '取消',
            type: 'warning'
          }
        ).then(() => {
          store.dispatch('LogOut').then(() => {
            location.reload() // 为了重新实例化vue-router对象 避免bug
          })
        })
      } else if (res.status === 1) {
        Message({
          message: res.content,
          type: 'error',
          duration: 5 * 1000
        })
      } else if (res.status === 20002) {
        Message({
          message: res.content,
          type: 'error',
          duration: 5 * 1000
        })
      }
      return Promise.reject(res)
    } else {
      if (res.count !== undefined) {
        return { count: res.count, data: res.data }
      }
      return res.data
    }
  },
  error => {
    // eslint-disable-next-line
//  console.log("err" + error); 
    Message({
      message: error.desc || '未知异常',
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)

export default service
